import pdb
import serial
import sys
import time
import datetime
import psycopg2

#mode: EMU|COM
mode = 'COM'

def parseContactId(raw):
    e = {}
    e['objId']      = raw[2:6]
    e['msgType']    = raw[6:7]
    e['msgCode']    = raw[7:10]
    e['group']      = raw[10:12]
    e['zone']       = raw[12:15]
    return e

def getLastEventId(cursor):
    try:
        q   = "SELECT MAX(eventid) FROM traffic"
        cursor.execute(q)
        rid = int(cursor.fetchall()[0][0])
        return rid + 1
    except: return 1

def storeEvent(connection, recid, event):
    c = connection.cursor()
    arrival = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
    alarmcode = event['msgType'] + event['msgCode']
    q = "INSERT INTO traffic (eventid, accountnumber, partitionnumber, alarmcode, priority, arrival, zone, source, receiver, line, active)" \
        "VALUES (%d, 0, 0, '%s', 10, '%s', '', 'xep%d', 00, 0, TRUE)" % (recid, alarmcode, arrival, recid)
    c.execute(q)
    connection.commit()

conn = psycopg2.connect('dbname=Securithor user=postgres')

if mode == 'EMU':
    e = parseContactId('180001R11002003')
    r = getLastEventId(conn.cursor())
    storeEvent(conn, r, e)
if mode == 'COM':
    p = serial.Serial(port=2, baudrate=1200, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=0)

    message = ''
    while True:
        try:
            d = p.readline()
            p.write('\x06')
            if d == '': continue
            for i in d:
                if ord(i) in [20, 32]:
                    msg = parseContactId(message)
                    r = getLastEventId(conn.cursor())
                    storeEvent(conn, r, msg)
                    print msg
                    message = ''
                else: 
                    message += i
        except: continue

    p.close()

